package com.fantastic.web.interceptors;

import com.fantastic.common.exception.AuthException;
import com.fantastic.common.exception.LoginException;
import com.fantastic.common.exception.enums.RespStatusInfo;
import com.fantastic.common.utils.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangl
 * @date 2022/10/25
 * 认证拦截器
 */
public class TokenAuthInterceptor implements HandlerInterceptor {
    /**
     * 通过此字符串拿到token的值
     */
    public static final String TOKEN_HEADER = "Authorization";
    /**
     * 值的前缀
     */
    public static final String TOKEN_PREFIX = "Bearer ";


    /**
     * 验证处理
     * @param request
     * @param response
     * @param handler handlerMethod
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 注意：如果遇到预检请求（OPTIONS），那么此时的handler是一个PreFlightHandler对象，
        // 这个对象专门用于处理预检，同时会设置跨域配置。所以当handler是PreFlightHandler对象但又不放行的话，
        // 那么预检请求最终不会在响应头设置跨域访问，所以就会产生跨域问题
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        //解析Token
        String token = request.getHeader(TOKEN_HEADER);
        if(token != null) {
            String jwt = token.replace(TOKEN_PREFIX, "");
            if(!"null".equals(jwt)) {
                try {
                    //验证token
                    JwtUtils.verify(jwt);
                    //获取载体中的用户ID
                    Integer uid = JwtUtils.getPayload(jwt, "uid", Integer.class);
                    //设置到请求作用域，可在Controller中的参数获取
                    request.setAttribute("uid", uid);
                    return true;
                } catch (SecurityException e) {
                    throw new AuthException(RespStatusInfo.JWT_SECURITY);
                } catch (MalformedJwtException e) {
                    throw new AuthException(RespStatusInfo.JWT_MALFORMED);
                } catch (ExpiredJwtException e) {
                    throw new AuthException(RespStatusInfo.JWT_EXPIRED);
                } catch (UnsupportedJwtException e) {
                    throw new AuthException(RespStatusInfo.JWT_UNSUPPORTED);
                }
            }
        }
        throw new LoginException(RespStatusInfo.LOGIN);
    }
}
